# This Python file uses the following encoding: utf-8

import paddle
from paddleocr import PaddleOCR, draw_ocr
import cv2
import os
import http.server
import socketserver
import numpy as np  # 添加此导入
import cgi  # 添加此导入
import json
from PySide6.QtGui import QImage
from PIL import Image, ImageDraw, ImageFont

#将pixmap转换为字节数组
def pixmap_to_byte_array(q_image, format='JPG'):
    width = q_image.width()
    height = q_image.height()
    ptr = q_image.constBits()
    arr = np.array(ptr).reshape(height, width, 3)
    arr = arr[:, :, :3]  # 去掉alpha通道
    return arr
def ndarray_to_qimage(arr: np.ndarray) -> QImage:
    # 确保数组是 uint8 类型且内存连续
    if arr.dtype != np.uint8:
        arr = arr.astype(np.uint8)
    arr = np.ascontiguousarray(arr)
    # 根据通道数确定 QImage 格式
    if arr.ndim == 2:
        # 灰度图
        qformat = QImage.Format_Grayscale8
    elif arr.shape[-1] == 3:
        # OpenCV 默认是 BGR，需转换为 RGB（如果输入为 BGR）
        arr = cv2.cvtColor(arr, cv2.COLOR_BGR2RGB)
        qformat = QImage.Format_RGB888
    elif arr.shape[-1] == 4:
        qformat = QImage.Format_RGBA8888
    else:
        raise ValueError("不支持的通道数:"+str(arr))
    print(str(arr.strides))
    # 创建 QImage
    return QImage(
        arr.data,         # 数据指针
        arr.shape[1],     # 宽度（列数）
        arr.shape[0],     # 高度（行数）
        arr.strides[0],   # 每行的字节数（自动计算）
        qformat           # 图像格式
    )
def draw_line(draw,a,b,score):
    draw.line([(a[0],a[1]),(b[0],b[1])],fill=(int(255*score),0,int(255*(1-score))),width=2)
def draw_box(draw,box,score):
    a,b,c,d = box
    draw_line(draw,a,b,score)
    draw_line(draw,b,c,score)
    draw_line(draw,c,d,score)
    draw_line(draw,d,a,score)
def draw_text(draw,text,box):
    #font_test = ImageFont.truetype("simsun.ttf", 1)
    #fontsize_width,fontsize_height = font_test.getbbox()
    size = (box[3][1]-box[0][1])/96*72
    font = ImageFont.truetype("simsun.ttf", size)
    draw.text((box[0][0],box[0][1]), text, font=font, fill=(255, 0, 0))
    pass
#将识别结果画到原始图像上
def orgin_draw_ocr(imageData,result):
    # 根据通道数确定 QImage 格式
    if imageData.shape[-1] == 3:
        # OpenCV 默认是 BGR，需转换为 RGB（如果输入为 BGR）
        imageData = cv2.cvtColor(imageData, cv2.COLOR_BGR2RGB)
    image = Image.fromarray(imageData)
    draw = ImageDraw.Draw(image)
    boxes = [line[0] for line in result[0]]
    txts = [line[1][0] for line in result[0]]
    scores = [line[1][1] for line in result[0]]
    print(str(scores))
    for index in range(len(result[0])):
        box = boxes[index]
        draw_box(draw,box,scores[index])
        text = txts[index]
        draw_text(draw,text,box)
    return np.array(image)
class OcrTool:
    def __init__(self):
        pass
    @staticmethod
    def image_ocr(imageData):
        imageData = pixmap_to_byte_array(imageData)
        ocr = PaddleOCR(use_gpu = False, use_angle_cls=False, lang='ch')
        result = ocr.ocr(imageData, cls=True)
        print(result)
        print(type(result))
        print(type(result[0]))
        if result is None or result[0] is None:
            raise ValueError("没有找到可以识别的文字！")
        txts = [line[1][0] for line in result[0]]
        #result_image = draw_ocr(imageData,boxes, txts, scores,font_path='simsun.ttf')
        result_image = orgin_draw_ocr(imageData,result)
        return txts, ndarray_to_qimage(result_image)
